//
//  MessageViewController.m
//  RingLetter
//
//  Created by dllo on 16/3/17.
//  Copyright © 2016年 FenglyNuo. All rights reserved.
//

#import "MessageViewController.h"

@interface MessageViewController ()<UITableViewDelegate, UITableViewDataSource, EMChatManagerDelegate>

@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) NSMutableArray *conversations;

@end

@implementation MessageViewController

//@synthesize tableView, conversations;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.conversations = [NSMutableArray new];
    
    [self createTableView];
}


#pragma mark - 创建tableView 
- (void)createTableView {
    self.tableView = [[UITableView alloc] initWithFrame:self.view.frame style:(UITableViewStylePlain)];
    [self.view addSubview:_tableView];
    
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
}



#pragma mark - tableView Delegate & DataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _conversations.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    EMConversation *conversation = _conversations[indexPath.row];
    cell.textLabel.text = conversation.chatter;
    
    EMMessage * message = [conversation latestMessage];
    
    EMTextMessageBody * body = [message.messageBodies lastObject];
    
    cell.detailTextLabel.text = body.text;
    
    return cell;
}



# pragma mark - Chat Manager Delegate
/**
 *  当收到信息时的回调方法
 *
 *  @param message 信息构造体
 */
- (void)didReceiveMessage:(EMMessage *)message {
    [self reloadConversations];
}



#pragma mark - Receive Buddy
/**
 *  当收到好友请求的回调方法
 *
 *  @param username 来自请求的账号
 *  @param message  携带的请求信息
 */
- (void)didReceiveBuddyRequest:(NSString *)username message:(NSString *)message {
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:[NSString stringWithFormat:@"收到来自%@的请求", username] message:message preferredStyle:(UIAlertControllerStyleAlert)];
    
    UIAlertAction * acceptAction = [UIAlertAction actionWithTitle:@"好" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction *  action) {
        
        EMError * error;
        
        // 同意好友请求的方法
        if ([[EaseMob sharedInstance].chatManager acceptBuddyRequest:username error:&error] && !error) {
            
            NSLog(@"发送同意成功");
        }
    }];
    
    UIAlertAction * rejectAction = [UIAlertAction actionWithTitle:@"滚" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
        
        EMError * error;
        
        // 拒绝好友请求的方法
        if ([[EaseMob sharedInstance].chatManager rejectBuddyRequest:username reason:@"滚, 快滚!" error:&error] && !error) {
            
            NSLog(@"发送拒绝成功");
        }
        
    }];
    
    [alertController addAction:acceptAction];
    [alertController addAction:rejectAction];
    
    [self showDetailViewController:alertController sender:nil];
}




#pragma mark - reload Conversations
/** 
 * 刷新数据的方法
 */
- (void)reloadConversations {
    [_conversations removeAllObjects];
    
    [_conversations addObjectsFromArray:[[EaseMob sharedInstance].chatManager loadAllConversationsFromDatabaseWithAppend2Chat:YES]];
    
    [_tableView reloadData];
}

// 消息页面
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:dispatch_get_main_queue()];
    
    self.tabBarController.title = @"消息";
    
    [self reloadConversations];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:YES];
    
    [[EaseMob sharedInstance].chatManager removeDelegate:self];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
